"use strict"

let assert    = require('assert')
    ,debug    = require('debug')('models')
    ,log4js   = require('log4js')
    ,logger   = log4js.getLogger();

let mongoose = require('mongoose');
let config = require('../config')();

mongoose.Promise = require('bluebird');

/** set schemas **/
let Account   = require('./Account');
let Domain    = require('./Domain');
let User      = require('./User');
let Client    = require('./Client');
let QywxAccessToken = require("./QywxAccessToken");
let QywxNounce = require("./QywxNounce");


mongoose.connect(config.mongodb.conn);

let db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
  console.log("we are connected!");
  if( config.debug === true ){
    db.db.dropDatabase(function(err, result){
      /**
       *  Initialize default data
       */
      var seedUser = new User({
        firstName:  'Admin',
        lastName: 'Super',
        username: 'admin',
        password: 'admin123456',
        email:  'lei.he@aivics.com',
        mobile: '13764211365',
        activated: true,
      });

      var promise = seedUser.save();

      promise.then(function(user){
        //create account
        return Account.create({
          name: "aivics"
        });
      })
      .then(function(account){
        debug(account);
        var promise = Client.generateClientAsync(account);
        assert.ok(promise instanceof require('bluebird'));
        return promise;
      })
      .then(function(client){
        debug(client);
        return Domain.create({
          name: "qywx-admin",
          account: client.account,
          clients: [client],
          qywx: {
            corpId: "wx42c1a7f89c4a258d"
            ,corpSecret: "BrMySu4oO_J2psgOkMKaZ0K6NexnI0pNeOPC9F-L5nARiJqSLYY_7I9NVWL0YGca"
          }
        });
      })
      .catch(function(err){
        debug(err);
      });
    });
  }
});


exports.db          = db;
exports.Account     = Account;
exports.Domain      = Domain;
exports.User        = User;
exports.Client      = Client;
exports.QywxAccessToken = QywxAccessToken;
exports.QywxNounce  = QywxNounce;
